package com.fancy.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fancy.common.DeviceTypeEnum;
import com.fancy.common.security.MD5;
import com.fancy.common.StringUtil;

public class RequestUtils extends ServletRequestUtils {
	
	public static String JUYIXIAN_COOKIE_CHATID = "juyixian_chatid";
	
	public static String JUYIXIAN_COOKIE_LOGIN_TYPE = "juyixian_login_type";
	
	public static String JUYIXIAN_COOKIE_VOTE_RAND = "juyixian_vote_rand";

	public static boolean getBoolean(final String paramName) {
		return getBoolean(paramName, false);
	}

	public static boolean getBoolean(final String paramName, final boolean defaultVal) {
		return ServletRequestUtils.getBooleanParameter(getRequest(), paramName, defaultVal);
	}

	public static long getLong(final String paramName) {
		return getLong(paramName, 0L);
	}

	public static long getLong(final String paramName, final long defaultVal) {
		return ServletRequestUtils.getLongParameter(getRequest(), paramName, defaultVal);
	}

	public static int getInt(final String paramName) {
		return getInt(paramName, 0);
	}

	public static int getInt(final String paramName, final int defaultVal) {
		return ServletRequestUtils.getIntParameter(getRequest(), paramName, defaultVal);
	}

	public static String getString(final String paramName) {
		return getString(paramName, "");
	}

	public static String getString(final String paramName, final String defaultVal) {
		return ServletRequestUtils.getStringParameter(getRequest(), paramName, defaultVal);
	}

	/**
	 * 取得 Request 对象
	 * 
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	/**
	 * 取得客户端的IP地址
	 * 
	 * @return
	 */
	public static String getRemoteIp() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		try {
			ip = ip.split(",")[0];
		} catch (Exception e) {
			ip = request.getRemoteHost();
		}
		return ip;
	}
	
	/*
     * @return 本机IP
     * @throws SocketException
     */
	public static String getRealIp() throws SocketException {
        String localip = null;// 本地IP，如果没有配置外网IP则返回它
        String netip = null;// 外网IP
        Enumeration<NetworkInterface> netInterfaces =
            NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if (!ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else if (ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                    localip = ip.getHostAddress();
                }
            }
        }
        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }

	/**
	 * 获取用户代理字符串
	 * 
	 * @return
	 */
	public static String getUserAgent() {
		return getRequest().getHeader("User-Agent");
	}

	/**
	 * 判断平台
	 * 
	 * @return
	 */
	public static DeviceTypeEnum getDeviceType() {
		String userAgent = getRequest().getHeader("User-Agent");
		return StringUtil.getDeviceType(userAgent);
	}
	
	/**
	 * 获取管理后台Web Service url
	 * 
	 * @return
	 */
	public static String getAdminWS() {
		return String.format("http://%s/ws", Config.getString("admin.ws.host"));
	}
	/**
	 * 验证密钥
	 * @param str
	 * @param keymd5
	 * @return
	 */
	public static boolean key_verify(String str,String keymd5){
		//if(keymd5.equals(MD5.md5(str+Config.getString("juyixian.ws.secretkey")+getRemoteIp()))){
		if(keymd5.equals(MD5.md5(str+Config.getString("juyixian.ws.secretkey")))){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 生成密钥
	 * @param str
	 * @return
	 */
	public static String keymd5_create(String str) throws SocketException {
		//return MD5.md5(str+Config.getString("juyixian.ws.secretkey")+getRealIp());
		return MD5.md5(str+Config.getString("juyixian.ws.secretkey"));
	}
	
	/*************Cookie操作************/
	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
	    Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
	    Map<String,Cookie> cookieMap = ReadCookieMap(request);
	    if(cookieMap.containsKey(name)){
	        Cookie cookie = (Cookie)cookieMap.get(name);
	        return cookie;
	    }else{
	        return null;
	    }   
	}
	 
	 
	 
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
	    Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    return cookieMap;
	}
}
